<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Think\Model;

/**
 * 定价模块功能
 * @author Scor <1006792421@qq.com>
 * @time 2016-3-20
 */
class DingjiaController extends AdminController {
    /**
     * 基础成本录入
     */
    public function addbaseprice(){
        $batch=I('batch');
        $id_arr=I('id');
        $erp_pname_arr=I('erp_pname');
        $erp_spec_arr=I('erp_spec');
        $base_price_arr=I('base_price');
        $sg_base_price_arr=I('sg_base_price');
        $calculate_type_arr=I('calculate_type');
        $total_weight_arr=I('total_weight');
        $total_num_arr=I('total_num');
        $BIN_arr=I('BIN');
        $valid=false;
        $valid=(array_vaild($id_arr)===false)?$valid:true;
        $valid=(array_vaild($erp_pname_arr)===false)?$valid:true;
        $valid=(array_vaild($erp_spec_arr)===false)?$valid:true;
        $valid=(array_vaild($base_price_arr)===false)?$valid:true;
        $valid=(array_vaild($sg_base_price_arr)===false)?$valid:true;
        $valid=(array_vaild($calculate_type_arr)===false)?$valid:true;
        $valid=(array_vaild($total_weight_arr)===false)?$valid:true;
        $valid=(array_vaild($total_num_arr)===false)?$valid:true;
        $valid=(array_vaild($BIN_arr)===false)?$valid:true;
        if($valid===true){
            $this->error("数据不完整，请重新确认");
        }
        $model=M('dj_base_price');
        $commit=true;
        $model->startTrans();
        for($i=0;$i<count($BIN_arr);$i++){
            $data=array(
                'id'=>$id_arr[$i],
                'erp_pname'=>$erp_pname_arr[$i],
                'erp_spec'=>$erp_spec_arr[$i],
                'base_price'=>$base_price_arr[$i],
                'sg_base_price'=>$sg_base_price_arr[$i],
                'BIN'=>$BIN_arr[$i],
                'batch'=>$batch,
                'calculate_type'=>$calculate_type_arr[$i],
                'total_num'=>$total_num_arr[$i],
                'total_weight'=>$total_weight_arr[$i],
                'createAt'=>time(),
                'uid'=>UID
            );
            $res=$model->add($data,array(),true);
            if(!$res){
                $commit=false;
            }
        }
        if($commit){
            $model->commit();
            $this->success('基础成本录入成功');
        }else{
            $model->rollback();
            $this->err('基础成本录入成功');

        }
    }
    public function addpro(){
        $this->display();
    }
    /**
     * 定价清单
     */
    public function prolist(){
        $batch=date('Ymd',time());
        $this->batch=$batch;
        $this->display();
    }
    /**
     * 所有售价展示
     */
    public function batchlist(){
        $sql="select batch,count(id) cnt from gr_dj_base_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="批次列表";
        $this->display();
    }
    public function baseprice($batch){
        $map['batch']=$batch;
        $res=$this->lists('dj_base_price',$map);
        foreach($res as $k=>$v){
            $BIN='2'.substr($v['BIN'],1,4);
            $unit=get_spec_forward_unit($v['erp_spec']);
            $sql="select * from gr_material_product where BIN like '".$BIN."%' and spec like '%".$unit."/%' and status=1";
            $model=new Model();
            $subres=$model->query($sql);
            $res[$k]['zjnum']=count($subres);
            $res[$k]['zjlist']=$subres;
        }
        $this->assign('_list',$res);
        $this->batch=$batch;
        $this->title="规格定价";
        $this->display();
    }
    public function basePriceDel($id=0){
        $map['id']=$id;
        M('dj_base_price')->where($map)->delete();
        $this->success("删除成功");
    }
    /**
     *规格定价
     */
    public function sellspecprice(){
        $this->display();
    }
    /**
     * 新规格定价
     */
    public function addspecprice($id="",$batch=""){
        $this->batchid=$id;
        $this->batch=$batch;
        $this->title="规格定价";
        $this->display();
    }
    /**
     * 规格售价删除
     * @param $id
     */
    public function sellpricedel($id){
        if($id){
            $map['id']=$id;
            if(M('dj_spec_price')->where($map)->delete()){
                $this->success("删除成功");
            }else{
                $this->error("删除失败");
            }
        }else{
            $this->error("删除失败");
        }

    }
    /**
     * 销售价格展示
     */
    public function sellpricedetail($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="all";
        $this->display();
    }
    public function sellpricesc(){
        $sql="select batch,count(id) cnt from gr_dj_spec_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="商城售价";
        $this->display();
    }
    public function sellpriceyg(){
        $sql="select batch,count(id) cnt from gr_dj_spec_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="员工售价";
        $this->display();
    }
    public function sellpriceqsy(){
        $sql="select batch,count(id) cnt from gr_dj_spec_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="企事业售价";
        $this->display();
    }
    public function sellpricegyd(){
        $sql="select batch,count(id) cnt from gr_dj_spec_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="果饮店售价";
        $this->display();
    }
    public function sellpricegyds(){
        $sql="select batch,count(id) cnt from gr_dj_spec_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="广源丁山售价";
        $this->display();
    }
    public function sellpricesg(){
        $sql="select batch,count(id) cnt from gr_dj_base_price where delflag=0 group by batch order by batch desc ";
        $model=new Model();
        $res=$model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow,$page->listRows";
        $res=$model->query($sql);
        $this->assign('_list',$res);
        $this->title="果饮店售价";
        $this->display();
    }
    /**
     * 基础定价商品数据录入
     */
    public function addprolist($batch="",$edit_status=0,$adapter="",$phone="",$market="",$adapte_date="",$pre_date="",$real_date="",$total_trans_fee="",$total_goods_fee=""){
        $pname_arr=I('pname');
        $spec_arr=I('spec');
        $BIN_arr=I('BIN');
        $total_num_arr=I('total_num');
        $unit_num_price_arr=I('unit_num_price');
        $total_weight_arr=I('total_weight');
        $unit_weight_price_arr=I('unit_weight_price');
        $spec_num_arr=I('spec_num');
        $spec_weight_arr=I('spec_weight');
        $total_box_fee_arr=I('total_box_fee');
        $unit_trans_fee_arr=I('unit_trans_fee');
        $loss_arr=I('loss');
        $percent_arr=I('percent');
        $base_price_arr=I('base_price');
        $sg_base_price_arr=I('sg_base_price');
        $sg_base_pure_price_arr=I('sg_base_pure_price');
        $count_type_arr=I('count_type');
        $cost_off=I('cost_off');
        //件数：total_num
        //件价：unit_num_price
        //总重：total_weight
        //每斤单价：unit_weight_price
        //每件个数：spec_num
        //每件净重：spec_weight
        //总箱费：total_box_fee
        //单箱运费：unit_trans_fee
        //损耗：loss
        //食用率：percent


        //        dump(I());
        //        dump($pname_arr);
        //        dump($spec_arr);
        //        dump($unit_weight_arr);
        //        dump($box_weight_arr);
        //        dump($total_weight_arr);
        //        dump($spec_number_arr);
        //        dump($spec_price_arr);
        //        dump($extra_fee_arr);
        //        dump($total_fee_arr);
        //        dump($BIN_arr);
        //        return;
        //数据非空验证

        $valid=false;
        $valid=(array_vaild($pname_arr)===false)?$valid:true;
        $valid=(array_vaild($spec_arr)===false)?$valid:true;
        $valid=(array_vaild($BIN_arr)===false)?$valid:true;
        $valid=(array_vaild($total_num_arr)===false)?$valid:true;
        $valid=(array_vaild($unit_num_price_arr)===false)?$valid:true;
        $valid=(array_vaild($total_weight_arr)===false)?$valid:true;
        $valid=(array_vaild($spec_num_arr)===false)?$valid:true;
        $valid=(array_vaild($spec_weight_arr)===false)?$valid:true;
        $valid=(array_vaild($total_box_fee_arr)===false)?$valid:true;
        $valid=(array_vaild($unit_trans_fee_arr)===false)?$valid:true;
        $valid=(array_vaild($loss_arr)===false)?$valid:true;
        $valid=(array_vaild($percent_arr)===false)?$valid:true;
        $valid=(array_vaild($sg_base_pure_price_arr)===false)?$valid:true;
        $valid=(array_vaild($sg_base_price_arr)===false)?$valid:true;
        $valid=(array_vaild($base_price_arr)===false)?$valid:true;
        $valid=(array_vaild($unit_weight_price_arr)===false)?$valid:true;
        $valid=(array_vaild($count_type_arr)===false)?$valid:true;
        $valid=(array_vaild($cost_off)===false)?$valid:true;
        if($valid===true){
            $this->error("数据不完整，请重新确认");
        }
        $batch_data=array(
            "batch"=>$batch,
            "adapter"=>$adapter,
            "phone"=>$phone,
            "market"=>$market,
            "adapte_date"=>$adapte_date,
            "pre_date"=>$pre_date,
            "real_date"=>$real_date,
            "total_trans_fee"=>$total_trans_fee,
            "total_goods_fee"=>$total_goods_fee,
            "createAt"=>time(),
            "updateAt"=>time(),
            "uid"=>UID
        );
        $dataList=[];
        //件运费
        for($i=0;$i<count($pname_arr);$i++){
            $dataList[]=array(
                'batch'=>$batch,
                'pname'=>$pname_arr[$i],
                'spec'=>$spec_arr[$i],
                'BIN'=>$BIN_arr[$i],
                'total_num'=>$total_num_arr[$i],
                'unit_num_price'=>$unit_num_price_arr[$i],
                'total_weight'=>$total_weight_arr[$i],
                'unit_weight_price'=>$unit_weight_price_arr[$i],
                'spec_num'=>$spec_num_arr[$i],
                'spec_weight'=>$spec_weight_arr[$i],
                'total_box_fee'=>$total_box_fee_arr[$i],
                'unit_trans_fee'=>$unit_trans_fee_arr[$i],
                'createAt'=>time(),
                'updateAt'=>time(),
                'base_price'=>$base_price_arr[$i],
                'sg_base_price'=>$sg_base_price_arr[$i],
                'sg_base_pure_price'=>$sg_base_pure_price_arr[$i],
                'loss'=>$loss_arr[$i],
                'percent'=>$percent_arr[$i],
                'unit_trans_fee'=>$unit_trans_fee_arr[$i],
                'uid'=>UID,
                'count_type'=>$count_type_arr[$i],
                'cost_off'=>$cost_off[$i]
            );
        }
        $res=M('dj_batch_goods')->addAll($dataList);
        M('dj_batch')->add($batch_data);

        if($res){
            $this->success("清单录入成功");
        }else{
            $this->error("系统错误，请重试");
        }
    }
    /**
     * 果然详情列表
     */
    public function batchdetail($batch=""){
        $this->batch=$batch;
        $this->title="果然成本定价";
        $this->display();
    }
    /**
     * 果然详情列表
     */
    public function sgbatchdetail($batch=""){
        $map['batch']=$batch;
        $res=M('Dj_base_price')->where($map)->select();
        $this->assign('_list',$res);
        $this->batch=$batch;
        $this->title="世果售价";
        $this->display();
    }
    /**
     * 商品删除
     */
    public function editpro($batch=""){
        $this->display();
    }
    /**
     * 基础价格导出
     * @param string $batch
     */
    public function proExport() {
        $model=new Model();
        $where=" and batch='".I('batch')."'";
        $sql="select batch,BIN,erp_pname,erp_spec,base_price,total_num,total_weight from gr_dj_base_price where 1=1".$where;
        $data=$model->query($sql);
        if ($data){
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("批次","编码","商品名","规格","基础成本","总件数","总重");

            $title = "初算成本统计";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    /**
     * 世果定价导出
     */
    public function sgproExport($batch="") {
        $model=new Model();
        if($batch!=""){
            $where=" and batch='".$batch."'";
        }
        $sql="select batch,BIN,erp_pname,erp_spec,total_num,total_weight,sg_base_price from gr_dj_base_price where 1=1".$where;
        $data=$model->query($sql);

        for($i=0;$i<count($data);$i++){
            $data[$i]['fiveBox']=spec_number_format($data[$i]['sg_base_price'],1,1.03,true);
            $data[$i]['threeBox']=spec_number_format($data[$i]['sg_base_price'],1,1.07,true);
            $data[$i]['oneBox']=spec_number_format($data[$i]['sg_base_price'],1,1.1,true);
        }
        if ($data){
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("批次","编码","商品名","规格","箱数","总重","世果成本","上浮3%（5箱）","上浮7%（3箱）","上浮10%（1箱）");

            $title = "初算成本统计";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    /**
     * 运营销售价格展示
     * @param $batch
     */
    public function sellpricedetailsc($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="sc";
        $this->display();
    }
    /**
     * 员工销售价格展示
     * @param $batch
     */
    public function sellpricedetailyg($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="yg";
        $this->display();
    }
    /**
     * 企事业单位
     * @param $batch
     */
    public function sellpricedetailqsy($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="qsy";
        $this->display();
    }
    /**
     * 果饮店售价
     * @param $batch
     */
    public function sellpricedetailgyd($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="gyd";
        $this->display();
    }
    /**
     * 广源丁山售价
     * @param $batch
     */
    public function sellpricedetailgyds($batch){
        $map['batch']=$batch;
        $res=$this->lists("dj_spec_price",$map,"createAt desc");
        $this->_list=$res;
        $this->batch=$batch;
        $this->user="gyds";
        $this->display();
    }
    /**
     * 规格价格新增
     */
    public function addsellspec(){
        $aBatch=I('batch');
        $aPname=I('pname');
        $aBIN=I('BIN');
        $aBasePrice=I('base_price');
        $aProcessFee=I('process_fee');
        $aGrTransFee=I('gr_trans_fee');
        $aPackageFee=I('package_fee');
        $aSpecPriceSc=I('spec_price_sc');
        $aSpecPriceYg=I('spec_price_yg');
        $aSpecPriceGyd=I('spec_price_gyd');
        $aSpecPriceQsy=I('spec_price_qsy');
        $aSpecPricePf=I('spec_price_pf');
        $aSpecPriceGyds=I('spec_price_gyds');
        $aDataList=[];
        for($i=0;$i<count($aBatch);$i++){
            $aDataList[]=array(
                'batch'=>$aBatch[$i],
                'pname'=>$aPname[$i],
                'BIN'=>$aBIN[$i],
                'base_price'=>$aBasePrice[$i],
                'process_fee'=>$aProcessFee[$i],
                'gr_trans_fee'=>$aGrTransFee[$i],
                'package_fee'=>$aPackageFee[$i],
                'spec_price_sc'=>$aSpecPriceSc[$i],
                'spec_price_yg'=>$aSpecPriceYg[$i],
                'spec_price_gyd'=>$aSpecPriceGyd[$i],
                'spec_price_qsy'=>$aSpecPriceQsy[$i],
                'spec_price_gyds'=>$aSpecPriceGyds[$i],
                'spec_price_pf'=>$aSpecPricePf[$i],
                'createAt'=>time(),
                'updateAt'=>time(),
                'uid'=>UID
            );
        }
        if(M('dj_spec_price')->addAll($aDataList)){
            $this->success("保存成功",U('dingjia/batchlist'));
        }else{
            $this->error("保存失败",U('dingjia/batchlist'));
        }
    }
    public function search($pname="",$BIN=""){
        $map['pname']=array('like',"%".$pname."%");
        $map['BIN']=array('like',$BIN."%");
        $res=$this->lists('dj_spec_price',$map,'batch desc');
        $this->_list=$res;
        $this->title="";
        $this->display();
    }
    public function searchbaseprice($pname="",$BIN=""){
        $map['erp_pname']=array('like',"%".$pname."%");
        $map['BIN']=array('like',$BIN."%");
        $res=$this->lists('dj_base_price',$map,'batch desc');
        $this->title="基础价格";
        $this->_list=$res;
        $this->display();
    }
    public function searchsgprice($pname="",$BIN=""){
        $map['erp_pname']=array('like',"%".$pname."%");
        $map['BIN']=array('like',$BIN."%");
        $res=$this->lists('dj_base_price',$map,'batch desc');
        $this->_list=$res;
        $this->title="世果价格";
        $this->display();
    }
    /**
     * 总销售价导出
     * @param string $batch
     */
    public function sellpriceexport($batch="",$user=""){
        $model=new Model();
        if($batch!=""){
            $where=" and a.batch='".$batch."'";
        }
        switch($user){
            case "all":
                $fields="a.batch,a.pname,b.spec,a.base_price,a.process_fee,a.gr_trans_fee,a.package_fee,FORMAT(a.spec_price_sc,2),FORMAT(a.spec_price_gyd,2),FORMAT(a.spec_price_yg,2),FORMAT(a.spec_price_qsy,2),FORMAT(a.spec_price_pf,2),FORMAT(a.spec_price_gyds,2)";
                $aHeadArr=array("批次","商品名","规格","基础价格","手工费","快递费","打包费","运营成本120%（含运）","果饮店105%（不含运）","员工115%（不含运）","企事业120%（不含运）","批发125%（不含运）","广源丁山140%（不含运）");
                break;
            case "gyd":
                $fields="a.batch,a.pname,b.spec,FORMAT(a.spec_price_gyd,2)";
                $aHeadArr=array("批次","商品名","规格","果饮店105%（不含运）");
                break;
            case "yg":
                $fields="a.batch,a.pname,b.spec,FORMAT(a.spec_price_yg,2)";
                $aHeadArr=array("批次","商品名","规格","员工陈静115%（不含运）");
                break;
            case "qsy":
                $fields="a.batch,a.pname,b.spec,FORMAT(a.spec_price_qsy,2)";
                $aHeadArr=array("批次","商品名","规格","企事业120%（不含运）");
                break;
            case "gyds":
                $fields="a.batch,a.pname,b.spec,FORMAT(a.spec_price_gyds,2)";
                $aHeadArr=array("批次","商品名","规格","广源丁山140%（不含运）");
                break;
            case "sc":
                $fields="a.batch,a.pname,b.spec,FORMAT(a.spec_price_sc,2)";
                $aHeadArr=array("批次","商品名","规格","运营成本120%（含运）");
                break;
            default:
                $this->error("导出数据错误");
                return;
                break;
        }
        $sql="select ".$fields." from  gr_dj_spec_price a,gr_material_product b where 1=1 and a.BIN=b.BIN".$where;
        $data=$model->query($sql);
        if ($data){
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = $aHeadArr;

            $title = "初算成本统计";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    /**
     * 内部调用方法
     * @param $fileName
     * @param $headArr
     * @param $data
     * @param $title
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exceptions
     */
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $objActSheet->getColumnDimension('a')->setWidth(20);
                $objActSheet->getColumnDimension('b')->setWidth(25);
                $objActSheet->getColumnDimension('c')->setWidth(15);
                $objActSheet->getColumnDimension('d')->setWidth(15);
                $objActSheet->getColumnDimension('e')->setWidth(15);
                $objActSheet->getColumnDimension('f')->setWidth(15);
                $objActSheet->getColumnDimension('g')->setWidth(15);
                $objActSheet->getColumnDimension('h')->setWidth(15);
                $objActSheet->getColumnDimension('i')->setWidth(15);
                $objActSheet->getColumnDimension('j')->setWidth(15);
                $objActSheet->getColumnDimension('k')->setWidth(15);
                $objActSheet->getColumnDimension('l')->setWidth(15);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    /**
     * ajax获取批次中商品
     */
    public function ajaxGetBasePrice($batch=""){
        $map['batch']=$batch;
        $res=M('dj_base_price')->where($map)->order("createAt desc")->select();
        $this->ajaxReturn($res);
    }
    /**
     * ajax获取所有批次
     */
    public function ajaxgetallbatch($limit=100){
        $sql="select batch from gr_dj_base_price  GROUP BY batch";
        $model=new Model();
        $res=$model->query($sql);
        $this->ajaxReturn($res);
    }
    /**
     * ajax获取批次非商品信息
     */
    public function ajaxgetbatchinfo($batch){
        $map['batch']=$batch;
        $res=M('dj_batch')->where($map)->find();
        $this->ajaxReturn($res);
    }
    /**
     * ajax删除指定基础定价商品
     * @param $id
     */
    public function ajaxdelbatchgood($id){
        $map['id']=$id;
        $res=M('dj_batch_goods')->where($map)->delete();
        $this->ajaxReturn($res);
    }
    public function AjaxGetBasePriceById($id){
        $map['id']=$id;
        $res=M('dj_base_price')->where($map)->select();
        $this->ajaxReturn($res);
    }
    public function AjaxGetBasePriceByBatch($batch){
        $map['batch']=$batch;
        $res=M('dj_base_price')->where($map)->select();
        $this->ajaxReturn($res);
    }
    public function AjaxGetZjList($BIN="",$unit=""){
        $sql="select * from gr_material_product where BIN like '".$BIN."%' and spec like '%".$unit."/%' and status=1";
        $model=new Model();
        $res=$model->query($sql);
        $this->ajaxReturn($res);
    }
    public function AjaxGetSellPrice($priceNoFee,$BIN){
        $model=M('Subpro_productstock');
        $subSql="select ifnull(sum(b.num*c.unitprice),0) as subpro_fee from
              gr_material_product_subpro b,gr_subpro_productstock c
              where b.BIN=$BIN and c.BIN=b.subpro_id and c.dpid=999";
        $subRes=$model->query($subSql);
        $feeSql="select trans_fee,process_fee from gr_material_product_fee where BIN=$BIN";
        $feeRes=$model->query($feeSql);
        $data['subpro_fee']=$subRes[0]['subpro_fee'];
        $data['trans_fee']=$feeRes[0]['trans_fee'];
        $data['process_fee']=$feeRes[0]['process_fee'];
        $this->ajaxReturn($data);
    }
    public function ajaxPostQuickBasePriceSave($data){
        $dataRes=json_decode($data,true);
        $model=M('Dj_base_price');
        $dataRes['calculate_type']=$dataRes['calculateType'];
        $dataRes['updateAt']=NOW_TIME;
        $dataRes['uid']=UID;
        if($model->add($dataRes,[],true)){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }
}
